/********************************************************************************
 * Project Name		[JavaSE_Fundamentals]
 * File Name     	[PrimativeDataTypeConversion.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package basicGrammar;

/**
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class PrimativeDataTypeConversion {

	/**
	 * 基本类型数据的自动转换<br/>
	 * 
	 * 规则: 两种类型是兼容类型; 目标类型的范围要比源类型的范围大<br/>
	 */
	public static void autoConvert() {
		char c = 'a';
		byte b = 10;
		short s = b;
		int i = s;
		long l = i;
		float f = 10F;
		double d = f;

		int i2 = c;

		System.out.println("char c = " + c);
		System.out.println("byte b = " + b);
		System.out.println("short s = " + s);
		System.out.println("int i = " + i);
		System.out.println("long l = " + l);
		System.out.println("float f = " + f);
		System.out.println("double d = " + d);
		System.out.println("int i2 = " + i2);
		System.out.println();
	}

	/**
	 * 当float转换为double时, 有时会出现不相等的情况<br/>
	 * 
	 * 原因: 在类型转换时, 操作数都是二进制的形式, 浮点型无法用二进制精确表示<br/>
	 */
	public static void floatConvertToDouble() {
		float f = 1.7F;
		double d = f;
		System.out.println("f = " + f + "\td = " + d);

		float f2 = (float) d;
		System.out.println("f2 = " + f2);
		System.out.println();
	}

	/**
	 * 基本类型数据的强制转换[造型]<br/>
	 * 
	 * 规则: 当两种类型不兼容或者, 目标类型比源类型的范围小, 就要进行强制类型转换<br/>
	 * 布尔类型数据和其他类型数据无法互相转换, 如果想转换的话可以采用条件表达式(booleanCondition) ? 1 : 0<br/>
	 * 强制类型转换可能引起结果精度的丢失<br/>
	 * 强制类型转换时会发生"截断取模"的现象, 如byte b = (byte)300;其最终的值是44<br/>
	 * 
	 * 强制类型转换发生在运行期<br/>
	 */
	public static void forceConvert() {
		double d = 123.45D;
		float f = (float) d;
		long l = (long) d;
		int i = (int) d;
		short s = (short) d;
		byte b = (byte) d;

		System.out.println("double d = " + d);
		System.out.println("float f = " + f);
		System.out.println("long l = " + l);
		System.out.println("int i = " + i);
		System.out.println("short s = " + s);
		System.out.println("byte b = " + b);

		/*
		 * 首先对d2进行截断操作, 值变为508, 然后对256进行取模, 得到结果
		 */
		double d2 = 508.8D;
		b = (byte) d2;
		System.out.println(b);
		System.out.println();
	}

	public static void main(String[] args) {
		autoConvert();
		floatConvertToDouble();
		forceConvert();
	}
}
